<?php

namespace App\Morefun\Prize;

use App\Entities\VoucherCode;
use Illuminate\Container\Container;

class VoucherCodeSynchronizer
{
    /**
     * @var \Redis
     */
    protected $redis;

    public function write($prizeId)
    {
        $this->redis()->pipeline(function ($redis) use ($prizeId) {
            $codes = VoucherCode::query()->where('prize_id', $prizeId)
                ->pluck('code');

            $key = sprintf('voucher:codes:%s', $prizeId);

            foreach ($codes as $code) {
                $redis->sAdd($key, $code);
            }
        });
    }

    /**
     * @return \Redis
     */
    protected function redis()
    {
        if (!$this->redis) {
            $this->redis = Container::getInstance()->make('redis');
        }

        return $this->redis;
    }
}